import React from "react";
import  {
    createSlice
} from "@reduxjs/toolkit";
import {useSelector} from "react-redux";
export type TPanes = {
    title: string,
    key: string,
    closable: boolean
}
export type TPage = {
    current:number,
    pageSize:number,
    total:number
}
type TInitialState = {
    panes:TPanes[],
    pageInfo: TPage,
    loading: boolean
}
const initialState: TInitialState= {
    panes: [
        {
            title: "主页",
            key: '/',
            closable: false
        }
    ],
    pageInfo:{
        // current:1,
        current: localStorage.current ? localStorage.current : 1,//保证在第二页查看医院详情时，返回时依然是第二页
        pageSize:5,
        total:1
    },
    loading:false
}
const commonSlice = createSlice({
    name: "common",
    initialState,

    reducers: {
        addPanes(state, {payload}) {
            // state.panes.push(payload)
            const info:TPanes = state.panes.find((v:TPanes)=>v.key === payload.key) as TPanes;
            if(!info){
                state.panes.push(payload);
            }
        },
        delPanes(state, {payload}) {
            state.panes.splice(payload,1)
        },
        changeLoading(state,{payload}){
            // console.log(1111111,payload);
            state.loading = payload;
        },
        changePageInfo(state,{payload}){
            state.pageInfo = payload;
        },
        // 1.根据路径来改变tital payload: {pathname: , title}
        changeTitleByKey(state, {payload}) {
            let info: TPanes = state.panes.find((v:any) => v.key === payload.key) as TPanes;
            info.title = payload.title;
        },
        // 2通过key,删除对应的panes ---->对应详情页返回并关闭按钮
        delPanesByKey(state,{payload}){
            const index = state.panes.findIndex(v=>v.key === payload);
            state.panes.splice(index,1);
        }
    }
})
export const {addPanes, delPanes, changeLoading,changePageInfo, delPanesByKey, changeTitleByKey} = commonSlice.actions;
export const useSelectCommon = () => useSelector((state: any) => state.common);
export  default  commonSlice.reducer;